package com.ftg.learn.mall.service.impl;

import com.ftg.learn.mall.dto.PmsProductParam;
import com.ftg.learn.mall.dto.PmsProductResult;
import com.ftg.learn.mall.entity.PmsProduct;
import com.ftg.learn.mall.entity.PmsProductAttributeValue;
import com.ftg.learn.mall.entity.PmsSkuStock;
import com.ftg.learn.mall.mapper.*;
import com.ftg.learn.mall.service.IPmsProductAttributeValueService;
import com.ftg.learn.mall.service.IPmsProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ftg.learn.mall.service.IPmsSkuStockService;
import com.ftg.learn.util.ResEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品信息 服务实现类
 * </p>
 *
 * @author mallCommon
 * @since 2022-04-19
 */
@Service
public class PmsProductServiceImpl extends ServiceImpl<PmsProductMapper, PmsProduct> implements IPmsProductService {

    @Autowired
    IPmsSkuStockService iPmsSkuStockService;

    @Autowired
    IPmsProductAttributeValueService iPmsProductAttributeValueService;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    PmsBrandMapper pmsBrandMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    PmsProductCategoryMapper pmsProductCategoryMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    PmsProductMapper pmsProductMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    PmsSkuStockMapper pmsSkuStockMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    PmsProductAttributeValueMapper pmsProductAttributeValueMapper;


    /**
     * 商品添加
     * @param productParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = SQLException.class)
    public boolean insert(PmsProductParam productParam) {
        // 创建商品
        PmsProduct product = productParam;
        product.setProductId(null);
        product.setBrandName(pmsBrandMapper.findOneBrandName(productParam.getBrandId()));
        product.setProductCategoryName(pmsProductCategoryMapper.findOneCategoryName(productParam.getProductCategoryId()));
        product.setDeleteStatus(0);
        product.setVerifyStatus(0);
        this.save(product);
        Long productId = product.getProductId();
        // 处理sku的编码
        List<PmsSkuStock> skuStockList = productParam.getSkuStockList();
        handleSkuStockCode(skuStockList,productId);
        // 添加sku库存信息
        relateAndInsertList(iPmsSkuStockService, skuStockList, productId);
//        for (PmsSkuStock skuStock : skuStockList){
//            skuStock.setProductId(productId);
//            iPmsSkuStockService.save(skuStock);
//        }
        // 添加商品参数,添加自定义商品规格
        List<PmsProductAttributeValue> productAttributeValues =  productParam.getProductAttributeValueList();
        relateAndInsertList(iPmsProductAttributeValueService, productAttributeValues, productId);
//        for (PmsProductAttributeValue value : productAttributeValues){
//            value.setProductId(productId);
//            iPmsProductAttributeValueService.save(value);
//        }
        // 当添加了一个商品的时候，对应其品牌表中的商品信息数量+1
        pmsBrandMapper.updateProductCount(product.getBrandId());
        // 当添加了一个商品的时候，对应其产品表中的商品信息数量+1
        pmsProductCategoryMapper.updateProductCount(product.getProductCategoryId());
        return true;
    }

    /**
     * 处理sku的编码
     * @param skuStockList
     * @param productId
     */
    private void handleSkuStockCode(List<PmsSkuStock> skuStockList, Long productId) {
        if(CollectionUtils.isEmpty(skuStockList)) {
            return;
        }
        for(int i=0;i<skuStockList.size();i++){
            PmsSkuStock skuStock = skuStockList.get(i);
            if(StringUtils.isBlank(skuStock.getSkuCode())){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                StringBuilder sb = new StringBuilder();
                //日期
                sb.append(sdf.format(new Date()));
                //四位商品id
                sb.append(String.format("%04d", productId));
                //三位索引id
                sb.append(String.format("%03d", i+1));
                skuStock.setSkuCode(sb.toString());
            }
        }
    }

    /**
     * 建立和插入关系表操作
     *
     * @param service       可以操作的dao
     * @param dataList  要插入的数据
     * @param productId 建立关系的id
     */
    private void relateAndInsertList(Object service, List dataList, Long productId) {
        try {
            if (CollectionUtils.isEmpty(dataList)) {
                return;
            }
            Method insertList = service.getClass().getMethod("save", Object.class);
            for (Object item : dataList) {
                Method setProductId = item.getClass().getMethod("setProductId", Long.class);
                setProductId.invoke(item, productId);
                insertList.invoke(service, item);
            }
        } catch (Exception e) {
//            LOGGER.warn("创建产品出错:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 根据商品id获取商品编辑信息
     * @param pid
     * @return
     */
    @Override
    public PmsProductResult getUpdateInfo(Long pid) {
        return pmsProductMapper.getUpdateInfo(pid);
    }

    /**
     * 更新商品
     * @param pmsProductParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = SQLException.class)
    public boolean update(PmsProductParam pmsProductParam) {
        // 更新商品信息
        PmsProduct product = new PmsProduct();
        BeanUtils.copyProperties(pmsProductParam,product);
        this.updateById(product);
        // 修改sku库存信息
        Long productId = product.getProductId();
        handleUpdateSkuStockList(productId,pmsProductParam);
        // 修改商品参数，添加自定义商品规格 （先删除，再添加）
        pmsProductAttributeValueMapper.delValue(productId);
        relateAndInsertList(iPmsProductAttributeValueService,pmsProductParam.getProductAttributeValueList(),productId);
        return true;
    }



    /**
     * 修改sku库存信息
     * @param pid
     * @param pmsProductParam
     */
    private void handleUpdateSkuStockList(Long pid,PmsProductParam pmsProductParam){
        // 当前的sku信息 --> 前台给你传的sku信息
        List<PmsSkuStock> newSkuList = pmsProductParam.getSkuStockList();
        // 如果前台的传入没有sku库存，直接删除此商品中所有已经包含的库存
        if (CollectionUtils.isEmpty(newSkuList)){
            // 获取此商品id对应的之前的所有sku信息 并 删除。
//            List<Long> oldSkuIds = pmsSkuStockMapper.findSkuStockId(pid);
            List<PmsSkuStock> oldSkuList = pmsSkuStockMapper.findSkuStock(pid);
            List<Long> oldSkuIds = oldSkuList.stream().map(PmsSkuStock::getSkuStockId).collect(Collectors.toList());
            iPmsSkuStockService.removeBatchByIds(oldSkuIds);
            return;
        }
        // 获取初始的sku信息
        List<PmsSkuStock> oldSkuList = pmsSkuStockMapper.findSkuStock(pid);
        // 获取需要新增的sku信息，前端库存不传id，则此条库存是需要新增的库存
        List<PmsSkuStock> insertSkuList = newSkuList.stream().filter(e -> e.getSkuStockId()==null).collect(Collectors.toList());
        // 获取需要修改的sku信息，前端库存传入了id，则此条库存是需要修改的库存
        List<PmsSkuStock> updateSkuList = newSkuList.stream().filter(e -> e.getSkuStockId()!=null).collect(Collectors.toList());
        List<Long> updateSkuIds = updateSkuList.stream().map(PmsSkuStock::getSkuStockId).collect(Collectors.toList());
        // 获取需要删除的sku信息，前端库存传入包含id的库存数据集合，初始sku不包含此集合中的需要修改的库存id就应该被删除
        List<PmsSkuStock> deleteSkuList = oldSkuList.stream().filter(e -> !updateSkuIds.contains(e.getSkuStockId())).collect(Collectors.toList());
        // 插入或者修改的库存数据，sku编码改动。不传sku编码就根据逻辑自动生成，传入就按照手动参数传。
        handleSkuStockCode(insertSkuList,pid);
        handleSkuStockCode(updateSkuList,pid);
        // 新增sku的处理
        if (!CollectionUtils.isEmpty(insertSkuList)){
            relateAndInsertList(iPmsSkuStockService, insertSkuList, pid);
        }
        // 修改sku的处理
        if (!CollectionUtils.isEmpty(updateSkuList)){
            for (PmsSkuStock stock : updateSkuList){
                iPmsSkuStockService.updateById(stock);
            }
        }
        // 删除sku的处理
        if (!CollectionUtils.isEmpty(deleteSkuList)){
            iPmsSkuStockService.removeBatchByIds(deleteSkuList);
        }
    }

    /**
     * 批量修改审核状态
     * @param ids
     * @param publishStatus
     * @return
     */
    @Override
    public int updateVerifyStatus(List<Long> ids, Long publishStatus) {
        int cishu = 0;
//        for (int i = 0,len = ids.size(); i<len;i++){
//            pmsProductMapper.updateVerifyStatus(Math.toIntExact(ids.get(i)),showStatus);
//            cishu++;
//        }
        for (Long id: ids) {
            pmsProductMapper.updateVerifyStatus(id,publishStatus);
            cishu++;
        }
        return cishu;
    }

    /**
     * 批量修改审核状态
     * @param ids
     * @param recommendStatus
     * @return
     */
    @Override
    public int updatePublishStatus(List<Long> ids, Long recommendStatus) {
        int cishu = 0;
        for (Long id: ids) {
            pmsProductMapper.updatePublishStatus(id,recommendStatus);
            cishu++;
        }
        return cishu;
    }


    /**
     * 批量修改删除状态
     * @param ids
     * @param deleteStatus
     * @return
     */
    @Override
    public int updateDeleteStatus(List<Long> ids, Long deleteStatus) {
        int cishu = 0;
        for (Long id: ids) {
            pmsProductMapper.updateDeleteStatus(id,deleteStatus);
            cishu++;
        }
        return cishu;
    }





}
